package com.homework.test01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author south wind
 * @version 1.0
 * @date 2025/4/7 19:00
 * @description 合并文件，a.txt和b.txt合并到c.txt中
 */
public class Merge_AB {
    public static void main(String[] args) {
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;
        FileOutputStream fos = null;
        try {
            //输入流
            fis1 = new FileInputStream("D:\\test\\a.txt");
            fis2 = new FileInputStream("D:\\test\\b.txt");
            //输出流
            fos = new FileOutputStream("D:\\test\\c.txt");
            byte[] bytes = new byte[1024];
            int len =0;
            while ((len = fis1.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }
            while ((len = fis2.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }
            System.out.println("合并完成");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源流
           try {
               if (fis1 != null) {
                   fis1.close();
               }
               if (fis2 != null) {
                   fis2.close();
               }
               if (fos != null) {
                   fos.close();
               }
           } catch (IOException e) {
               System.err.println("关闭流时出错: " + e.getMessage());
           }

        }
        //打印合并文件
            try {
                FileInputStream ff = new FileInputStream("D:\\test\\c.txt");
                byte[] b = new byte[1024];
                int len;

                StringBuilder sb = new StringBuilder();
                while ((len = ff.read(b)) != -1){
                    sb.append(new String(b,0,len));
                }
                System.out.println("合并文件为：");
                System.out.println(sb.toString());

            } catch (FileNotFoundException e) {
                System.err.println("合并后的文件未找到: " + e.getMessage());
        } catch (IOException e) {
                System.err.println("读取合并后文件时出错: " + e.getMessage());
            }
    }
}
